<template>
  <div v-if="show" class="channel-manager-overlay" @click="close">
    <div class="channel-manager" @click.stop>
      <div class="header">
        <h2>频道管理</h2>
        <button class="close-btn" @click="close">✕</button>
      </div>
      
      <div class="content">
        <!-- 我的频道 -->
        <div class="section">
          <div class="section-header">
            <h3>我的频道</h3>
            <span class="tip">点击进入频道 长按拖动排序</span>
          </div>
          <div class="channel-list">
            <div 
              v-for="channel in myChannels" 
              :key="channel.id"
              :class="['channel-item', { 'active': channel.id === activeChannelId }]"
              @click="selectChannel(channel)"
            >
              <span>{{ channel.name }}</span>
              <button 
                v-if="!channel.fixed" 
                class="delete-btn" 
                @click.stop="removeChannel(channel)"
              >
                ✕
              </button>
            </div>
          </div>
        </div>

        <!-- 推荐频道 -->
        <div class="section">
          <div class="section-header">
            <h3>推荐频道</h3>
            <span class="tip">点击添加频道</span>
          </div>
          <div class="channel-list">
            <div 
              v-for="channel in recommendChannels" 
              :key="channel.id"
              class="channel-item add-btn"
              @click="addChannel(channel)"
            >
              <span>{{ channel.name }}</span>
              <span class="plus">+</span>
            </div>
          </div>
        </div>
      </div>

      <div class="footer">
        <button class="save-btn" @click="saveChannels">完成</button>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, watch } from 'vue'
import { tagAPI, userAPI } from '../api'

const props = defineProps({
  show: {
    type: Boolean,
    default: false
  },
  activeChannelId: {
    type: Number,
    default: null
  }
})

const emit = defineEmits(['close', 'channelChange', 'update:show'])

// 所有可用频道
const allChannels = ref([])
// 我的频道ID列表
const myChannelIds = ref([])

// 我的频道（计算属性）
const myChannels = computed(() => {
  return allChannels.value
    .filter(ch => myChannelIds.value.includes(ch.id))
    .map(ch => ({
      ...ch,
      fixed: ch.id === 1 // 推荐频道固定不可删除
    }))
})

// 推荐频道（未添加的频道）
const recommendChannels = computed(() => {
  return allChannels.value.filter(ch => !myChannelIds.value.includes(ch.id))
})

// 加载所有标签作为频道
const loadChannels = async () => {
  try {
    const response = await tagAPI.getTags()
    if (response.data.code === 0) {
      allChannels.value = response.data.data.map(tag => ({
        id: tag.id,
        name: tag.name,
        icon: tag.icon
      }))
    }
  } catch (error) {
    console.error('加载频道失败:', error)
  }
}

// 加载用户已选频道
const loadMyChannels = async () => {
  try {
    // 先尝试从localStorage获取
    const localChannels = localStorage.getItem('myChannels')
    if (localChannels) {
      myChannelIds.value = JSON.parse(localChannels)
      return
    }

    // 从后端获取用户标签
    const response = await userAPI.getUserTags()
    if (response.data.code === 0 && response.data.data) {
      myChannelIds.value = response.data.data.map(tag => tag.id)
      
      // 如果为空，默认添加"推荐"频道
      if (myChannelIds.value.length === 0) {
        myChannelIds.value = [1] // 假设ID为1是推荐频道
      }
      
      // 保存到localStorage
      localStorage.setItem('myChannels', JSON.stringify(myChannelIds.value))
    }
  } catch (error) {
    console.error('加载我的频道失败:', error)
    // 设置默认频道
    myChannelIds.value = [1]
    localStorage.setItem('myChannels', JSON.stringify(myChannelIds.value))
  }
}

// 选择频道
const selectChannel = (channel) => {
  emit('channelChange', channel)
  close()
}

// 添加频道
const addChannel = (channel) => {
  if (!myChannelIds.value.includes(channel.id)) {
    myChannelIds.value.push(channel.id)
  }
}

// 移除频道
const removeChannel = (channel) => {
  if (channel.fixed) {
    alert('该频道不可删除')
    return
  }
  
  const index = myChannelIds.value.indexOf(channel.id)
  if (index > -1) {
    myChannelIds.value.splice(index, 1)
  }
  
  // 如果删除的是当前激活的频道，切换到推荐
  if (channel.id === props.activeChannelId) {
    const firstChannel = myChannels.value[0]
    if (firstChannel) {
      emit('channelChange', firstChannel)
    }
  }
}

// 保存频道设置
const saveChannels = async () => {
  try {
    // 保存到localStorage
    localStorage.setItem('myChannels', JSON.stringify(myChannelIds.value))
    
    // 同步到后端（可选）
    try {
      await userAPI.setUserTags(myChannelIds.value)
    } catch (error) {
      console.warn('同步频道到后端失败:', error)
    }
    
    close()
  } catch (error) {
    console.error('保存频道失败:', error)
  }
}

// 关闭弹窗
const close = () => {
  emit('update:show', false)
  emit('close')
}

// 监听show变化，加载数据
watch(() => props.show, (newVal) => {
  if (newVal) {
    loadChannels()
    loadMyChannels()
  }
})
</script>

<style scoped>
.channel-manager-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  z-index: 9999;
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 20px;
}

.channel-manager {
  background: #fff;
  border-radius: 16px;
  width: 100%;
  max-width: 600px;
  max-height: 80vh;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

.header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 20px;
  border-bottom: 1px solid #e9ecef;
}

.header h2 {
  font-size: 18px;
  font-weight: 600;
  margin: 0;
}

.close-btn {
  background: none;
  border: none;
  font-size: 24px;
  color: #666;
  cursor: pointer;
  padding: 4px;
  line-height: 1;
}

.content {
  flex: 1;
  overflow-y: auto;
  padding: 20px;
}

.section {
  margin-bottom: 32px;
}

.section:last-child {
  margin-bottom: 0;
}

.section-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 16px;
}

.section-header h3 {
  font-size: 16px;
  font-weight: 600;
  margin: 0;
  color: #333;
}

.tip {
  font-size: 12px;
  color: #999;
}

.channel-list {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(100px, 1fr));
  gap: 12px;
}

.channel-item {
  position: relative;
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 10px 16px;
  background: #f5f5f5;
  border-radius: 8px;
  font-size: 14px;
  color: #333;
  cursor: pointer;
  transition: all 0.3s;
  user-select: none;
}

.channel-item:hover {
  background: #e9ecef;
}

.channel-item.active {
  background: #fff0f6;
  color: #ff2442;
  font-weight: 500;
}

.channel-item.add-btn {
  border: 1px dashed #d9d9d9;
  background: transparent;
  color: #666;
}

.channel-item.add-btn:hover {
  border-color: #ff2442;
  color: #ff2442;
  background: #fff0f6;
}

.delete-btn {
  position: absolute;
  top: -6px;
  right: -6px;
  width: 18px;
  height: 18px;
  border-radius: 50%;
  background: #ff4d4f;
  color: white;
  border: none;
  font-size: 12px;
  line-height: 1;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 0;
  opacity: 0;
  transition: opacity 0.2s;
}

.channel-item:hover .delete-btn {
  opacity: 1;
}

.plus {
  margin-left: 4px;
  font-size: 16px;
  font-weight: bold;
}

.footer {
  padding: 16px 20px;
  border-top: 1px solid #e9ecef;
}

.save-btn {
  width: 100%;
  padding: 12px;
  background: #ff2442;
  color: white;
  border: none;
  border-radius: 8px;
  font-size: 16px;
  font-weight: 500;
  cursor: pointer;
  transition: background 0.3s;
}

.save-btn:hover {
  background: #e01e3c;
}

@media (max-width: 640px) {
  .channel-manager {
    max-width: 100%;
    max-height: 90vh;
    border-radius: 16px 16px 0 0;
    margin-top: auto;
  }

  .channel-list {
    grid-template-columns: repeat(auto-fill, minmax(80px, 1fr));
    gap: 8px;
  }

  .channel-item {
    padding: 8px 12px;
    font-size: 13px;
  }
}
</style>


